package com.lj.sys.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lj.common_web.annotation.ResponseResultVo;
import com.lj.sys.annotation.DataScope;
import com.lj.sys.param.SysDataScopePageParam;
import com.lj.sys.param.SysDataScopeSaveParam;
import com.lj.sys.param.SysDataScopeUpdateParam;
import com.lj.sys.result.SysDataScopeInfoResult;
import com.lj.sys.result.SysDataScopePageResult;
import com.lj.sys.result.UrlPathResult;
import com.lj.sys.service.SysDataScopeService;
import com.lj.sys.service.SysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

/**
 * <p>
 * 数据范围表 前端控制器
 * </p>
 *
 * @author lj
 * @since 2025-08-06 18:24:15
 */
@RestController
@RequestMapping("/sys/sys_data_scope")
@ResponseResultVo
@Tag(name = "数据范围表 管理")
public class SysDataScopeController {

    @Resource
    private SysMenuService menuService;
    @Resource
    private List<RequestMappingHandlerMapping> requestMappingHandlerMappingList;

    @Resource
    private SysDataScopeService sysDataScopeService;

    @GetMapping("/page")
    @SaCheckPermission("sys:sys_data_scope:list")
    @Operation(summary = "数据范围表 分页查询")
    public IPage<SysDataScopePageResult> page(@ParameterObject SysDataScopePageParam param) {
        return sysDataScopeService.page(param);
    }

    @GetMapping("/getUrlPath")
    @SaCheckPermission("sys:sys_data_scope:list")
    @Operation(summary = "当前用户所有的接口")
    public List<UrlPathResult> getUrlPath() {
        long userId = StpUtil.getLoginIdAsLong();
        // 获取用户拥有的所有接口权限
        Set<String> permissionSet = menuService.getAllPermission(userId);
        if (CollUtil.isEmpty(permissionSet)) {
            return Collections.emptyList();
        }
        List<UrlPathResult> result = new ArrayList<>();
        // 获取所有接口
        for (RequestMappingHandlerMapping handlerMapping : requestMappingHandlerMappingList) {
            Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
            for (Map.Entry<RequestMappingInfo, HandlerMethod> handlerMethodEntry : handlerMethods.entrySet()) {
                // 判断接口是否有数据范围注解标识
                DataScope dataScope = handlerMethodEntry.getValue().getMethod().getAnnotation(DataScope.class);
                if (dataScope == null) {
                    continue;
                }
                // 判断当前用户是否拥有该接口权限
                SaCheckPermission saCheckPermission = handlerMethodEntry.getValue().getMethod().getAnnotation(SaCheckPermission.class);
                if (saCheckPermission == null || ArrayUtil.isEmpty(saCheckPermission.value())) {
                    continue;
                }
                if (!CollUtil.containsAny(permissionSet, Arrays.asList(saCheckPermission.value()))) {
                    // 用户没有当前接口的权限
                    continue;
                }
                PathPatternsRequestCondition pathPatternsCondition = handlerMethodEntry.getKey().getPathPatternsCondition();
                if (pathPatternsCondition == null) {
                    continue;
                }
                String urlPath = handlerMethodEntry.getKey().getPathPatternsCondition().getFirstPattern().getPatternString();
                String apiName = "";
                Operation operation = handlerMethodEntry.getValue().getMethod().getAnnotation(Operation.class);
                if (operation != null) {
                    apiName = operation.summary();
                }
                result.add(new UrlPathResult(apiName, urlPath));
            }
        }
        // 排序
        CollUtil.sortByProperty(result, LambdaUtil.getFieldName(UrlPathResult::getUrlPath));
        return result;
    }

    @GetMapping("/info/{id}")
    @SaCheckPermission("sys:sys_data_scope:info")
    @Operation(summary = "数据范围表 信息")
    public SysDataScopeInfoResult info(@PathVariable("id") @Parameter(name = "id", description = "数据范围表 id") Long id) {
        if (id == null) {
            return null;
        }
        return sysDataScopeService.info(id);
    }

    @PostMapping("/save")
    @SaCheckPermission("sys:sys_data_scope:save")
    @Operation(summary = "数据范围表 新增")
    public void save(@RequestBody @Validated SysDataScopeSaveParam param) {
        sysDataScopeService.save(param);
    }

    @PostMapping("/update")
    @SaCheckPermission("sys:sys_data_scope:update")
    @Operation(summary = "数据范围表 更新")
    public void update(@RequestBody @Validated SysDataScopeUpdateParam param) {
        sysDataScopeService.update(param);
    }

    @PostMapping("/delete")
    @SaCheckPermission("sys:sys_data_scope:delete")
    @Operation(summary = "数据范围表 删除")
    public void delete(@RequestBody List<Long> ids) {
        sysDataScopeService.delete(ids);
    }

}

